import request from "../../utils/request"; //axios
let cart = {
  state: {
    dataList: [
      {
        id: 1,
        name: "小米",
        num: 1,
        checked: false,
      },
    ], //购物车数据
  },

  getters: {
    total(state) {
      //获取总数量
      //统计总数量
      let num = 0;
      state.dataList.forEach((item) => {
        if (item.checked) {
          num += item.num;
        }
      });
      return num;
    },
    allprice(state) {
      //获取总价
      return;
    },
    goodsTotal(state) {
      //获取购物车的长度
      return state.dataList.length;
    },
  },

  mutations: {
    init(state, data) {
      //初始化购物车数据
      state.dataList = data;
    },

    add(state, data) {
      state.dataList.push(data);
    },

    del(state, id) {
      state.dataList = state.dataList.filter((item) => item.id != id);
    },
  },

  actions: {
    //发请求获取购物车数据
    getData({ commit }, payload) {
      request
        .get("xxx", {
          params: payload,
        })
        .then((res) => {
          commit("init", res.data);
        });
    },

    //添加商品
    addItem({ commit }, payload) {
      request.post("xxx", payload).then((res) => {
        if (res.data.flag) {
          //插入成功:数据库已经新增一个订单
          commit("add", payload);
        }
      });
    },

    //删除
    delItem() {
      request.delete("xxx", payload).then((res) => {
        if (res.data.flag) {
          //删除:数据库已经删除一个订单
          commit("del", payload);
        }
      });
    },

    //修改数量
    edit() {},
  },
};

export default cart;
